﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Marbles.Core.Controls
{
    [ToolboxData("<{0}:AutoComplete runat=server></{0}:AutoComplete>")]
    public class AutoComplete : TextBox
    {
        public string Options
        {
            get
            {
                object obj = ViewState["options"]; if (obj == null) { return ""; }
                return obj.ToString();
            }
            set { ViewState["options"] = value; }
        }

        public Int32 MinimumLength { get { object obj = ViewState["MinLength"]; if (obj == null) { return 2; } return Convert.ToInt32(obj); } set { ViewState["MinLength"] = value; } }
        public string SourceUrl { get { object obj = ViewState["SourceUrl"]; if (obj == null) { return ""; } return obj.ToString(); } set { ViewState["SourceUrl"] = value; } }


        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            writer.AddAttribute("type", "text/javascript");
            writer.AddAttribute("language", "javascript");
            writer.RenderBeginTag(HtmlTextWriterTag.Script);

            writer.Write("$(\"#" + this.ClientID + "\" ).autocomplete({source:");
            if (string.IsNullOrEmpty(SourceUrl))
            {
                string[] args = Options.Split(',');
                writer.Write("[");
                for (int i = 0; i < args.Length; i++)
                {
                    if (i > 0) { writer.Write(", "); }
                    writer.Write("\"" + args[i] + "\"");
                }
                writer.Write("]");
            }
            else
            {
                writer.Write("\"" + this.SourceUrl + "\"");
            }

            writer.Write(", minLength:" + this.MinimumLength.ToString());
            writer.Write("})");
            writer.RenderEndTag();
        }
    }
}
